package cn.itcast.bos.service.base.impl;

import cn.itcast.bos.dao.base.CourierRepository;
import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.service.base.CourierService;
import org.apache.commons.lang.StringUtils;
import org.apache.xmlbeans.impl.store.Public2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.*;
import java.util.List;
import java.util.Set;

@Transactional
@Service
public class CourierServiceImpl implements CourierService {
	
	@Autowired
	private CourierRepository courierRepository;

	@Override
	public void save(Courier courier) {
		courierRepository.save(courier);
	}

	@Override
	public Page<Courier> findAll(Specification<Courier> spec, Pageable pageable) {
		return courierRepository.findAll(spec, pageable);
	}

	@Override
	public void update(Character deltag, String ids) {
		String[] arrs = ids.split(",");
		
		for (String string : arrs) {
			System.out.println(deltag);
			courierRepository.update(deltag,Integer.parseInt(string));
		}
		
	}

	@Override
	public List<Courier> noAssociationFixedArea() {

		Specification<Courier> specification = new Specification<Courier>() {
			@Override
			public Predicate toPredicate(Root<Courier> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				return cb.isEmpty(root.get("fixedAreas").as(Set.class));

			}
		};
		return courierRepository.findAll(specification);
	}

	@Override
	public List<Courier> findByFixedAreaId(final String fixedAreaId) {
		Specification<Courier> specification = new Specification<Courier>() {
			@Override
			public Predicate toPredicate(Root<Courier> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				Predicate p =null;
				if(StringUtils.isNotBlank(fixedAreaId)){
					SetJoin<Courier,FixedArea> join= root.join(root.getModel().getSet("fixedAreas",FixedArea.class), JoinType.INNER);
					p = cb.equal(join.get("id").as(String.class),fixedAreaId);
				}

				return p;

			}
		};

		return courierRepository.findAll(specification);
	}

}
